<template>
  <div ref="pieChartRef" class="w-1/1 h-1/1"></div>
</template>
<script setup lang="ts">
import type { EChartsOption } from "echarts";
import echarts from "@/plugins/echarts";
const pieChartRef = ref<ElRef>();
let echartRef: Nullable<echarts.ECharts> = null;

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  options: {
    type: Object,
    default() {
      return {};
    },
  },
});
watch(
  () => props.options,
  () => {
    setOptions();
  },
  { deep: true }
);
onMounted(() => {
  initChart();
});
onUnmounted(() => {
  echartRef?.dispose;
});
const initChart = () => {
  if (unref(pieChartRef) && props.options) {
    echartRef = echarts.init(unref(pieChartRef) as unknown as HTMLElement);
    setOptions();
  }
};

const setOptions = () => {
  if (unref(pieChartRef) && props.options) {
    const _seriesData: any = [];
    if (props.options.seriesData && props.options.seriesData.length > 0) {
      props.options.seriesData.forEach((item: any) => {
        _seriesData.push({
          value: item.value,
          name: item.name,
        });
      });
    }

    const _echartOption: EChartsOption = {
      title: {
        text: props.title,
        left: "left",
      },
      tooltip: {
        trigger: "item",
      },
      legend: {
        top:"40px",
        orient: "vertical",
        left: "right",
      },
      series: [
        {
          name: "",
          top: "30px",
          left: "0",
          width: "90%",
          type: "pie",
          radius: "70%",
          data: _seriesData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
    echartRef?.setOption(_echartOption);
  }
};
</script>
